﻿using BaseData.Domain;
using BaseData.ErrorCode;
using BaseData.Infrastructure.DTO;
using BaseData.Infrastructure.Interfaces;
using MD5Hash;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;


namespace BaseData.Infrastructure.User
{
    public class UserService : IUserService
    {
        private readonly IBaseRepository<Users> userRep;
        private readonly IBaseRepository<Roles> roleRep;
        private readonly IBaseRepository<UserRoles> userroleRep;

        public UserService(IBaseRepository<Users> userRep,IBaseRepository<Roles> roleRep,IBaseRepository<UserRoles> userroleRep)
        {
            this.userRep = userRep;
            this.roleRep = roleRep;
            this.userroleRep = userroleRep;
        }
        #region  用户角色
        /// <summary>
        /// 添加用户角色数据
        /// </summary>
        /// <param name="user"></param>
        /// <param name="rolelist"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> AddUserRole(Users user, List<int> rolelist)
        {
            try
            {
                //先判断用户名称是否存在
                var res = await userRep.GetAll().FirstOrDefaultAsync(x=>x.UserName==user.UserName);
                if (res != null)
                {
                    return -1;//用户名已存在
                }
                var result = 0;
                using (var tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    try
                    {
                        
                        user.Password = user.Password.GetMD5();
                        await userRep.AddAsync(user);
                        //保存添加用户id
                        var Uid = user.UsersId;
                        //添加用户角色表
                        foreach (var item in rolelist)
                        {
                            var ur = new UserRoles();
                            ur.UserId = Uid;
                            ur.RoleId = item;
                            result += await userroleRep.AddAsync(ur) >0  ? 1 : 0;
                        }
                        tran.Complete();
                        return result;
                    }
                    catch (Exception)
                    {

                        throw;
                    }
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 显示角色信息
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<List<Roles>> GetRoles()
        {
            var res = await roleRep.GetAll().ToListAsync();
            return res;
        }
        /// <summary>
        /// 显示用户信息下拉框
        /// </summary>
        /// <returns></returns>
        public async Task<List<Users>> GetUser()
        {
            return await userRep.GetAll().ToListAsync();
        }
        /// <summary>
        /// 显示用户管理
        /// </summary>
        /// <param name="index"></param>
        /// <param name="size"></param>
        /// <param name="userId"></param>
        /// <param name="level"></param>
        /// <param name="userTitle"></param>
        /// <param name="channel"></param>
        /// <returns></returns>
        public async Task<PaggingResult<List<Users>>> GetUsers(int index, int size, long? userId, string? level, string? userTitle, string? channel)
        {
            var res = await userRep.GetAll().ToListAsync();
            if (userId > 0)
            {
                res = res.Where(x => x.UsersId == userId).ToList();
            }
            if (!string.IsNullOrEmpty(level))
            {
                res = res.Where(x => x.Level == level).ToList();
            }
            if (!string.IsNullOrEmpty(userTitle))
            {
                res = res.Where(x => x.UserTitle == userTitle).ToList();
            }
            if (!string.IsNullOrEmpty(channel))
            {
                res = res.Where(x => x.Channel == channel).ToList();
            }
            int count = res.Count();
            int page = (int)Math.Ceiling(count * 1.0 / size);
            res = res.OrderBy(x => x.UsersId).Skip((index - 1) * size).Take(size).ToList();
            return new PaggingResult<List<Users>>
            {
                Count = count,
                Data = res,
                Pages = page,
            };
        }
        /// <summary>
        ///  显示角色
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<List<int>> GetUsersRoles(int userId)
        {
            var res = await userroleRep.GetAll().Where(x => x.UserId == userId).Select(x=>x.RoleId).ToListAsync();
            return res;
        }
        /// <summary>
        /// 修改用户角色
        /// </summary>
        /// <param name="users"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> UpdUser(Users users)
        {
            var res = await userRep.UpdateAsync (users);
            return res;
        }
        /// <summary>
        /// 软删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<int> UserDel(int id)
        {
            var res = await userRep.DelAsync(id);
            return res;
        }
        #endregion
        
        #region 角色
        public async Task<PaggingResult<List<Roles>>> GetRoleList(int index, int size, string? rolename)
        {
            var res = await roleRep.GetAll().ToListAsync();
            if (!string.IsNullOrEmpty(rolename))
            {
                res = res.Where(x => x.RoleName.Contains(rolename)).ToList();
            }
            int c = res.Count();
            int p = (int)Math.Ceiling(c * 1.0 / size);
            res = res.OrderBy(x=>x.RoleId).Skip((index-1)*size).Take(size).ToList();
            return new PaggingResult<List<Roles>>
            {
                Count = c,
                Pages = p,
                Data = res
            };
        }
        /// <summary>
        /// 添加角色
        /// </summary>
        /// <param name="role">实体</param>
        /// <returns>返回添加角色数据</returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<int> AddRole(Roles role)
        {
            role.RoleState = true;
            role.MemberCount = 10;
            role.UpdateTime = DateTime.Now;
            return roleRep.AddAsync(role);
        }
        /// <summary>
        /// 编辑角色信息
        /// </summary>
        /// <param name="role">实体</param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> UpdRole(Roles role)
        {
            role.RoleState = true;
            role.MemberCount = 10;
            role.UpdateTime = DateTime.Now;
            var res = await roleRep.UpdateAsync(role);
            return res;
        }
        /// <summary>
        /// 修改角色状态
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> UpdateRoleState(RoleStateDto dto)
        {
            var res = await roleRep.GetAll().FirstOrDefaultAsync(x => x.RoleId == dto.RoleId);
            res.RoleState = dto.RoleState;
            res.Remark = dto.Remark;
            return await roleRep.UpdateAsync(res);
        }
        /// <summary>
        /// 软删除角色
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> DelRole(int id)
        {
            var res = await roleRep.DelAsync(id);
            return res;
        }
        /// <summary>
        /// 获取角色
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Roles> GetRoles(int id)
        {
            var res = await  roleRep.GetById(id);
            return res;
        }
        #endregion
    }
}
